package web;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.naming.java.javaURLContextFactory;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;

import model.HelperJasperReport;

/**
 * Servlet implementation class ViewJasperReports
 */
public class ViewJasperReports extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ViewJasperReports() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HashMap<String, Object> parms = new HashMap<String, Object>();
		HelperJasperReport helperJasper = new HelperJasperReport();
		ServletOutputStream servletOutputStream = response.getOutputStream();
		InputStream pdfDefinitionStream = null;

		if (request.getServletPath().equals("/viewbill.do")) {
			int facturaId = Integer.parseInt(request.getParameter("id"));
			int type = Integer.parseInt(request.getParameter("t"));
			if (type == 1) {
				pdfDefinitionStream = helperJasper.getReportInputStream("reports/nir_test2.jasper");
			} else if (type == 2) {
				pdfDefinitionStream = helperJasper.getReportInputStream("reports/BonConsum.jasper");
			} else if (type == 3) {
				pdfDefinitionStream = helperJasper.getReportInputStream("reports/BonConsumMateriale.jasper");
			}
			parms.put("facturaId", facturaId);
		} else if (request.getServletPath().equals("/showsales.do")) {
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Date fromDate = null, toDate = null;
			try {
				fromDate = df.parse(request.getParameter("from"));
				toDate = df.parse(request.getParameter("from"));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			String reportType = request.getParameter("report");
			if (reportType.equals("c")) {
				pdfDefinitionStream = helperJasper.getReportInputStream("reports/SalesReportCompact.jasper");
			} else if (reportType.equals("d")) {
				pdfDefinitionStream = helperJasper.getReportInputStream("reports/SalesReportDetailed.jasper");
			}
			parms.put("fromDate", fromDate);
			parms.put("toDate", toDate);
		}

		try {
			JasperRunManager.runReportToPdfStream(pdfDefinitionStream, servletOutputStream, parms, helperJasper.getConnection());
			helperJasper.closeConnection();
		} catch (JRException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// , new JREmptyDataSource());

		response.setContentType("application/pdf");
		servletOutputStream.flush();
		servletOutputStream.close();

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HashMap<String, Object> parms = new HashMap<String, Object>();
		HelperJasperReport helperJasper = new HelperJasperReport();
		ServletOutputStream servletOutputStream = response.getOutputStream();
		InputStream pdfDefinitionStream = null;

		if (request.getServletPath().equals("/showsales.do")) {
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Date fromDate = null, toDate = null;

			String buttonName = "";
			Map<String, String[]> paramMap = request.getParameterMap();
			for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {
				/*
				 * Search for the button name as given in the 'value' attribute
				 * for the input tag
				 */
				if ("Compact".equals(entry.getValue()[0])) {
					buttonName = entry.getKey();
					break;
				} else if ("Detaliat".equals(entry.getValue()[0])) {
					buttonName = entry.getKey();
					break;
				}
			}

			try {
				fromDate = df.parse(request.getParameter("fromDate"));
				toDate = df.parse(request.getParameter("toDate"));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			if (buttonName.equals("Compact")) {
				pdfDefinitionStream = helperJasper.getReportInputStream("reports/SalesReportCompact.jasper");
			} else if (buttonName.equals("Detaliat")) {
				pdfDefinitionStream = helperJasper.getReportInputStream("reports/SalesReportDetailed.jasper");
			}
			parms.put("fromDate", fromDate);
			parms.put("toDate", toDate);
		} else if (request.getServletPath().equals("/showvanzari.do") || request.getServletPath().equals("/showcumparaturi.do")) {
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Date fromDate = null, toDate = null;
			int count = 1;
			String nameCondition = "", nameProducts = "", name = "";
			try {
				fromDate = df.parse(request.getParameter("fromDate"));
				toDate = df.parse(request.getParameter("toDate"));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			while ((name = request.getParameter(count + "_1")) != null) {
				if (count == 1) {
					nameCondition = "( prod.nume='";
					nameCondition += name + "'";
				} else {
					nameCondition += " OR prod.nume='" + name + "'";
				}
				count++;
				nameProducts += name + " ";
			}
			nameCondition += " ) ";
			if (request.getServletPath().equals("/showvanzari.do")) {
				pdfDefinitionStream = helperJasper.getReportInputStream("reports/SalesReportStats.jasper");
			} else if (request.getServletPath().equals("/showcumparaturi.do")) {
				pdfDefinitionStream = helperJasper.getReportInputStream("reports/BuysReportStats.jasper");
			}
			parms.put("fromDate", fromDate);
			parms.put("toDate", toDate);
			parms.put("nameCondition", nameCondition);
			parms.put("nameProducts", nameProducts);
		} else if (request.getServletPath().equals("/viewlog.do")) {
			parms.put("limita", Integer.parseInt(request.getParameter("limit")));
			pdfDefinitionStream = helperJasper.getReportInputStream("reports/AlterLogReport.jasper");
		} 

		try {
			JasperRunManager.runReportToPdfStream(pdfDefinitionStream, servletOutputStream, parms, helperJasper.getConnection());
			helperJasper.closeConnection();
		} catch (JRException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}// , new JREmptyDataSource());

		response.setContentType("application/pdf");
		servletOutputStream.flush();
		servletOutputStream.close();

	}
}
